<?php declare(strict_types=1);

namespace Reezy\APIToken;


use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;


class APITokenMiddleware implements MiddlewareInterface
{
    /**
     * @var APITokenManager
     */
    protected $manager;

    public function __construct(APITokenManager $manager)
    {
        $this->manager = $manager;
    }

    /**
     * Process an incoming server request.
     *
     * @param ServerRequestInterface $request
     * @param RequestHandlerInterface $handler
     *
     * @return ResponseInterface
     * @throws APITokenException
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        [$newRequest, $newToken] = $this->manager->check($request);

        if (empty($newToken)) {
            return $handler->handle($newRequest);
        } else {
            return $handler->handle($newRequest)->withHeader($this->manager->getHeaderTokenKey(), $newToken);
        }
    }
}
